package com.edu.test;
/*
 * @Author:princess
 * @Date 2023/10/26 10 26 8:41
 *
 */

import com.edu.bean.Student;
import com.edu.bean.User;
import org.junit.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class MyTest3 {
    /*
        通过反射获取到一个class文件中的构造方法
     */
    @Test
    public void test01() throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Class clazz = User.class;
        Constructor[] constructors = clazz.getConstructors();
        for (Constructor constructor : constructors) {
            System.out.println(constructor);
        }
        System.out.println();

        Constructor declaredConstructor = clazz.getDeclaredConstructor(String.class, String.class);
        declaredConstructor.setAccessible(true);
        Object o = declaredConstructor.newInstance("shufen", "123456");
        System.out.println(o);
        System.out.println();
    }

    @Test
    public void test02() throws InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchMethodException {
        Class clazz = Student.class;
        Constructor declaredConstructor = clazz.getDeclaredConstructor(int.class,String.class);
        declaredConstructor.setAccessible(true);
        Student s = (Student)declaredConstructor.newInstance(1,"zhangsan");
        System.out.println(s);

        Constructor constructor = clazz.getDeclaredConstructor();
        constructor.setAccessible(true);
        Student s2 = (Student) constructor.newInstance();
        System.out.println(s2);
    }
}
